﻿using Admin.ApplicationLib.Services;
using Minio;
using Swimj.Core.Providers;

namespace Admin.ApplicationLib.Providers
{
    public class MinioFileProvider : IFileProvider
    {
        private readonly MinioClient _minioClient;

        public MinioFileProvider(MinioClient minioClient)
        {
            _minioClient = minioClient;
        }

        public async Task UploadFile(Stream stream, string bucketName, string objectName,
            string contentType = "application/octet-stream")
        {
            try
            {
                // Make a bucket on the server, if not already present.
                var beArgs = new BucketExistsArgs()
                    .WithBucket(bucketName);
                bool found = await _minioClient.BucketExistsAsync(beArgs).ConfigureAwait(false);
                if (!found)
                {
                    var mbArgs = new MakeBucketArgs()
                        .WithBucket(bucketName);
                    await _minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false);
                }

                // Upload a file to bucket.
                var putObjectArgs = new PutObjectArgs()
                    .WithBucket(bucketName)
                    .WithObject(objectName)
                    .WithStreamData(stream)
                    .WithObjectSize(stream.Length)
                    .WithContentType(contentType);
                await _minioClient.PutObjectAsync(putObjectArgs).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}